package service

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"wechat01/basic/config"
	"wechat01/handler/request"
	"wechat01/pkg"
)

func SendSms(c *gin.Context) {
	var form request.SendSms
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	timeCount, _ := config.Rdb.Get(config.Ctx, "smsCodeTime_"+form.Phone).Int()
	if timeCount >= 3 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "同一手机号1分钟内最多发送3条验证码",
		})
		return
	}
	code := rand.Intn(900000) + 100000
	sms, err := pkg.SendSms(form.Phone, strconv.Itoa(code))
	if err != nil {
		return
	}
	if sms.Code != 2 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "验证码发送失败",
		})
		return
	}
	config.Rdb.Set(config.Ctx, "smsCode_"+form.Phone, code, time.Minute*5)
	config.Rdb.Incr(config.Ctx, "smsCodeTime_"+form.Phone)
	config.Rdb.Expire(config.Ctx, "smsCodeTime_"+form.Phone, time.Minute*1)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "验证码发送成功"})
	return
}
